package com.mzy.olddate.demo.map;

import com.mzy.olddate.demo.common.Student;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Ives
 * * @date 2021/8/16
 */
public class HashMapDemo {
  public static void main(String[] args) {
    System.out.println("---------------------------");
//    new HashMap<String, List<User>>();

    HashMap<Integer, Student> integerStudentHashMap = new HashMap<>();
    integerStudentHashMap.put(1, new Student(18, "黎明"));
    integerStudentHashMap.put(2, new Student(19, "黑暗"));

    forEach(integerStudentHashMap);

    forEachTwo(integerStudentHashMap);

    forEachThree(integerStudentHashMap);

    forEachThree(integerStudentHashMap);

  }

  /**
   * forEach循环。迭代entries对象
   * @param hashMap
   */
  public static void forEach(HashMap<Integer, Student> hashMap){
    for (Map.Entry<Integer, Student> entry:
            hashMap.entrySet()) {
      System.out.println(entry.getKey()+"####"+entry.getValue());
    }
  }

  /**
   * 使用For-Each迭代keys和values
   * @param hashMap
   */
  public static void forEachTwo(HashMap<Integer, Student> hashMap){

    for (Integer key: hashMap.keySet()) {
      System.out.println("Key = " + key);
    }

    for (Student value: hashMap.values()) {
      System.out.println("Value = " + value);
    }
  }

  /**
   * 使用Iterator迭代
   * @param hashMap
   */
  public static void forEachThree(HashMap<Integer, Student> hashMap){
    Iterator<Map.Entry<Integer, Student>> entryIterator = hashMap.entrySet().iterator();
    while (entryIterator.hasNext()){
      Map.Entry<Integer, Student> entry = entryIterator.next();
      Integer key = entry.getKey();
      Student value = entry.getValue();
      System.out.println("key:"+key+"  value:"+value);

    }
  }

  /**
   * 迭代keys并根据key获得values（低效的）
   * @param hashMap
   */
  public static void forFourth(HashMap<Integer, Student> hashMap){
    for (Integer key:hashMap.keySet()
         ) {
      Student student = hashMap.get(key);
      System.out.println("key:"+key+"  value:"+student);
    }
  }



}
